package com.good.cm.utils;

import com.good.cm.vo.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public  class CookieUtil {
    /**
     * 获取cookie
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request,String key){
        Cookie[] cookies = request.getCookies();
        System.out.println("获取cookie");
        String value="";
        //遍历Cookie数组
        if (cookies!=null && cookies.length>0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                String name = cookie.getName();
                if (name.equals(key)) {
                     value = cookie.getValue();
                }
            }
        }
        return  value;
    }

    /**
     * 获取cookie 用户iD
     * @param request
     * @return
     */
    public static String getCookieUserId(HttpServletRequest request){
       return  getCookie(request,"userId");
    }
    /**
     *客户端返回cookie
     * @param response
     * @param name
     * @param value
     */
    public static void addCookie(HttpServletResponse response, String name, String value) {
        System.out.println("开始添加cookie"+value);
        Cookie cookie = new Cookie(name, value);//trim() 方法用于删除字符串的头尾空白符。
        cookie.setMaxAge(60 * 60 * 24);// 设置为24小时 60秒*60分*24小时
        cookie.setPath("/");//因此cookie.setPath("/");之后，可以在webapp文件夹下的所有应用共享cookie，而cookie.setPath("/webapp/")是指设置的cookie只能在webapp应用下的获得
        System.out.println("已添加cookie");
        response.addCookie(cookie);//最后用response的addCookie()添加设置的cookie
    }
}
